"""商店设置路由模块"""
from flask import Blueprint, request, jsonify
from werkzeug.utils import secure_filename
import os
import traceback
from app.utils.decorators import login_required
from app.config import config
from app.database import get_db_connection

bp = Blueprint('store', __name__, url_prefix='/api')

def allowed_file(filename):
    """检查文件扩展名是否允许"""
    return '.' in filename and filename.rsplit('.', 1)[1].lower() in config.ALLOWED_EXTENSIONS

@bp.route('/store/settings', methods=['GET'])
@login_required
def get_store_settings():
    """获取商店设置"""
    connection = None
    cursor = None
    try:
        connection = get_db_connection()
        cursor = connection.cursor()
        cursor.execute('SELECT store_name_zh, store_name_uy FROM store_settings LIMIT 1')
        settings = cursor.fetchone()
        if settings:
            settings['logo_url'] = '/static/images/logo.jpeg'
        return jsonify(settings or {
            'store_name_zh': '伊善齐商店',
            'store_name_uy': 'ئىشەنچ دۇكان',
            'logo_url': '/static/images/logo.jpeg'
        })
    except Exception as e:
        return jsonify({'success': False, 'message': f'数据库操作失败: {str(e)}'}), 500
    finally:
        if cursor:
            cursor.close()
        if connection:
            connection.close()

@bp.route('/store/settings', methods=['POST'])
@login_required
def save_store_settings():
    """保存商店设置"""
    settings_data = request.json
    store_name_zh = settings_data.get('store_name_zh')
    store_name_uy = settings_data.get('store_name_uy')
    
    connection = None
    cursor = None
    try:
        connection = get_db_connection()
        cursor = connection.cursor()
        
        cursor.execute(
            'REPLACE INTO store_settings (id, store_name_zh, store_name_uy) VALUES (1, %s, %s)',
            (store_name_zh, store_name_uy)
        )
        connection.commit()
        
        return jsonify({'success': True, 'message': '商店设置保存成功'})
    except Exception as e:
        if connection:
            connection.rollback()
        return jsonify({'success': False, 'message': f'数据库操作失败: {str(e)}'}), 500
    finally:
        if cursor:
            cursor.close()
        if connection:
            connection.close()

@bp.route('/upload/logo', methods=['POST'])
@login_required
def upload_logo():
    """上传Logo"""
    if 'logo' not in request.files:
        return jsonify({'success': False, 'message': '没有文件被上传'}), 400
    
    file = request.files['logo']
    
    if file.filename == '':
        return jsonify({'success': False, 'message': '没有选择文件'}), 400
    
    if not allowed_file(file.filename):
        return jsonify({
            'success': False,
            'message': f'不允许的文件类型，只支持: {" ".join(config.ALLOWED_EXTENSIONS)}'
        }), 400
    
    if file.content_length and file.content_length > config.MAX_CONTENT_LENGTH:
        max_size_mb = config.MAX_CONTENT_LENGTH / (1024 * 1024)
        return jsonify({
            'success': False,
            'message': f'文件大小超过限制，最大允许 {max_size_mb:.2f}MB'
        }), 400
    
    try:
        filename = 'logo.jpeg'
        file_path = os.path.join('static', 'images', filename)
        
        images_dir = os.path.join('static', 'images')
        if not os.path.exists(images_dir):
            os.makedirs(images_dir)
        
        file.save(file_path)
        return jsonify({'success': True, 'message': 'Logo上传成功'})
    except Exception as e:
        return jsonify({'success': False, 'message': f'文件保存失败: {str(e)}'}), 500

